package com.unicorn.auth.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		System.out.println(path);
		HttpSession session = req.getSession();
		if (session.getAttribute("USER") == null && !path.startsWith("/login")&&!path.startsWith("/")
				&& !path.startsWith("/login.jsp")&&!isStaticResource(path)) {
			((HttpServletResponse) response).sendRedirect(req.getContextPath()
					+ "/login");
		} else {
			chain.doFilter(request, response);// 执行其他拦截器链
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	private boolean isStaticResource(String path) {
		return path.indexOf("static")<0;
	}

}
